<template>
  <div class="erp-account">
    <el-card shadow="never">
      <template #header>
        <div class="erp-account__header">
          <span>会计科目</span>
          <div>
            <el-button type="primary" size="small" @click="openCreate">新增</el-button>
            <el-button size="small" type="danger" :disabled="selectedRows.length === 0" @click="onBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" class="erp-account__search" @submit.prevent>
        <el-form-item label="科目编码">
          <el-input v-model="query.accountCode" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="科目名称">
          <el-input v-model="query.accountName" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="科目类型">
          <el-select v-model="query.accountType" placeholder="全部" clearable>
            <el-option value="ASSET" label="资产" />
            <el-option value="LIABILITY" label="负债" />
            <el-option value="EQUITY" label="权益" />
            <el-option value="REVENUE" label="收入" />
            <el-option value="EXPENSE" label="费用" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable>
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" size="small" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column prop="accountCode" label="科目编码" min-width="120" />
        <el-table-column prop="accountName" label="科目名称" min-width="200" />
        <el-table-column prop="parentId" label="父科目ID" min-width="120" />
        <el-table-column prop="accountType" label="科目类型" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.accountType === 'ASSET'" type="success">资产</el-tag>
            <el-tag v-else-if="row.accountType === 'LIABILITY'" type="warning">负债</el-tag>
            <el-tag v-else-if="row.accountType === 'EQUITY'" type="info">权益</el-tag>
            <el-tag v-else-if="row.accountType === 'REVENUE'" type="primary">收入</el-tag>
            <el-tag v-else-if="row.accountType === 'EXPENSE'" type="danger">费用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dcFlag" label="借贷方向" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.dcFlag === 'DEBIT'" type="success">借方</el-tag>
            <el-tag v-else-if="row.dcFlag === 'CREDIT'" type="warning">贷方</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="levelNum" label="层级" min-width="80" />
        <el-table-column prop="isLeaf" label="是否叶子" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.isLeaf === 1 ? 'success' : 'info'">{{ row.isLeaf === 1 ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="160" />
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该科目？" @confirm="onDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="erp-account__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <!-- 编辑抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="科目编码" prop="accountCode">
          <el-input v-model="form.accountCode" placeholder="请输入科目编码" />
        </el-form-item>
        <el-form-item label="科目名称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入科目名称" />
        </el-form-item>
        <el-form-item label="父科目ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="留空表示顶级科目" />
        </el-form-item>
        <el-form-item label="科目类型" prop="accountType">
          <el-select v-model="form.accountType" placeholder="请选择科目类型" style="width: 100%">
            <el-option value="ASSET" label="资产" />
            <el-option value="LIABILITY" label="负债" />
            <el-option value="EQUITY" label="权益" />
            <el-option value="REVENUE" label="收入" />
            <el-option value="EXPENSE" label="费用" />
          </el-select>
        </el-form-item>
        <el-form-item label="借贷方向" prop="dcFlag">
          <el-select v-model="form.dcFlag" placeholder="请选择借贷方向" style="width: 100%">
            <el-option value="DEBIT" label="借方" />
            <el-option value="CREDIT" label="贷方" />
          </el-select>
        </el-form-item>
        <el-form-item label="层级" prop="levelNum">
          <el-input-number v-model="form.levelNum" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否叶子" prop="isLeaf">
          <el-select v-model="form.isLeaf" placeholder="请选择" style="width: 100%">
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item>
          <div style="text-align: center; width: 100%;">
            <el-button type="primary" :loading="submitLoading" @click="onSubmit">保存</el-button>
            <el-button @click="drawerVisible = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { pageAccount, getAccount, createAccount, updateAccount, deleteAccount, type AccountDTO } from '@/api/erp/account'
import { ElMessage } from 'element-plus'

const list = ref<any[]>([])
const selectedRows = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{ accountCode?: string; accountName?: string; accountType?: string; status?: number | '' }>({
  accountCode: '',
  accountName: '',
  accountType: '',
  status: ''
})

const drawerVisible = ref(false)
const isEdit = ref(false)
const drawerTitle = ref('新增科目')
const formRef = ref<FormInstance>()
const form = reactive<AccountDTO>({
  accountCode: '',
  accountName: '',
  parentId: '',
  accountType: '',
  dcFlag: '',
  levelNum: 1,
  isLeaf: 1,
  status: 1,
  remark: ''
})
const rules: FormRules = {
  accountCode: [{ required: true, message: '请输入科目编码', trigger: 'blur' }],
  accountName: [{ required: true, message: '请输入科目名称', trigger: 'blur' }]
}
const submitLoading = ref(false)

const load = async () => {
  const res = await pageAccount({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    accountCode: query.accountCode || undefined,
    accountName: query.accountName || undefined,
    accountType: query.accountType || undefined,
    status: query.status === '' ? undefined : Number(query.status)
  })
  list.value = res?.data?.rows || []
  total.value = res?.data?.total || 0
}

const onPageChange = (p: number) => {
  pageNum.value = p
  load()
}
const onSizeChange = (s: number) => {
  pageSize.value = s
  pageNum.value = 1
  load()
}

const onSearch = () => {
  pageNum.value = 1
  load()
}

const onReset = () => {
  query.accountCode = ''
  query.accountName = ''
  query.accountType = ''
  query.status = ''
  onSearch()
}

const onSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

const openCreate = () => {
  isEdit.value = false
  drawerTitle.value = '新增科目'
  resetForm()
  drawerVisible.value = true
}

const openEdit = async (row: any) => {
  isEdit.value = true
  drawerTitle.value = '编辑科目'
  const res = await getAccount(String(row.accountId))
  Object.assign(form, {
    accountId: String(res?.data?.accountId),
    accountCode: res?.data?.accountCode || '',
    accountName: res?.data?.accountName || '',
    parentId: res?.data?.parentId ? String(res?.data?.parentId) : '',
    accountType: res?.data?.accountType || '',
    dcFlag: res?.data?.dcFlag || '',
    levelNum: res?.data?.levelNum || 1,
    isLeaf: res?.data?.isLeaf || 1,
    status: res?.data?.status ?? 1,
    remark: res?.data?.remark || ''
  })
  drawerVisible.value = true
}

const resetForm = () => {
  form.accountId = undefined
  form.accountCode = ''
  form.accountName = ''
  form.parentId = ''
  form.accountType = ''
  form.dcFlag = ''
  form.levelNum = 1
  form.isLeaf = 1
  form.status = 1
  form.remark = ''
  formRef.value?.clearValidate()
}

const onSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value && form.accountId) {
          await updateAccount(form.accountId, form)
          ElMessage.success('更新成功')
        } else {
          await createAccount(form)
          ElMessage.success('新增成功')
        }
        drawerVisible.value = false
        load()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const onDelete = async (row: any) => {
  try {
    await deleteAccount(String(row.accountId))
    ElMessage.success('删除成功')
    load()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const onBatchDelete = async () => {
  if (selectedRows.value.length === 0) return
  try {
    await Promise.all(selectedRows.value.map(row => deleteAccount(String(row.accountId))))
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    load()
  } catch (error) {
    ElMessage.error('批量删除失败')
  }
}

onMounted(load)
</script>

<style scoped lang="scss">
.erp-account {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

